<template>
    <div class="title">引流员工设置</div>
    <el-form
        ref="formRef"
        :model="formData"
        :rules="pageType == 'look' ? '' : rules"
        label-width="110px"
        :disabled="pageType == 'look'">
        <el-form-item label="引流员工" prop="employee_ids">
            <el-button type="primary" plain @click="openDepart">
                <el-icon><Plus /></el-icon>
                <span>添加员工</span>
            </el-button>
            <render-user-tags v-model:tags="employeeList" :closable="pageType !== 'look'" />
        </el-form-item>
        <el-form-item label="助力者员工分配" class="form-radio-item">
            <el-radio-group v-model="formData.employee_setting">
                <el-radio :label="3">
                    <span>随机分配</span>
                    <span class="form-tip"> 助力者添加的企业成员，为引流员工中的随机一位 </span>
                </el-radio>
                <el-radio :label="2">
                    <span>溯源员工</span>
                    <span class="form-tip">
                        助力者添加的企业成员，为分享客户所添加的引流员工（若分享客户的企微好友不在引流员工里，将随机分配）：如，客户A添加员工甲，分享给客户B后，客户B添加的也是员工甲，以此类推
                    </span>
                </el-radio>
            </el-radio-group>
        </el-form-item>
        <el-divider />
        <div class="title">客户打标</div>
        <el-form-item label="参与者打标">
            <el-button :disabled="formDisabled" @click="selecTag(1)">选择标签</el-button>
            <render-tags v-model:tags="AllTags" :closable="computedTagClosable" />
        </el-form-item>
        <el-form-item label="助力者打标">
            <el-button :disabled="formDisabled" @click="selecTag(2)">选择标签</el-button>
            <render-tags v-model:tags="helpTags" :closable="computedTagClosable" />
        </el-form-item>
        <el-form-item label="中奖者打标">
            <el-button :disabled="formDisabled" @click="selecTag(3)">选择标签</el-button>
            <render-tags v-model:tags="rewardTags" :closable="computedTagClosable" />
        </el-form-item>
        <el-form-item label="领奖者打标">
            <el-button :disabled="formDisabled" @click="selecTag(4)">选择标签</el-button>
            <render-tags v-model:tags="receiveTags" :closable="computedTagClosable" />
        </el-form-item>
        <el-form-item label="高级打标">
            <el-switch v-model="formData.isHight" :disabled="formDisabled"></el-switch>
        </el-form-item>
        <el-form-item v-if="formData.isHight" label="助力人数">
            <div class="assisted_num">
                <div class="assisted_card">
                    <el-card v-for="(item, index) in formData.tag" :key="item.help_num" class="card_box" shadow="never">
                        <template #header>
                            <div class="header">
                                <span class="header-tiltle">规则{{ index + 1 }}：</span>
                                <el-icon v-if="!formDisabled" style="cursor: pointer" @click="onDelete(index)">
                                    <delete />
                                </el-icon>
                            </div>
                        </template>
                        <el-form-item label-width="108px" label="助力人数超过">
                            <el-input-number
                                v-model="item.assist_num"
                                size="small"
                                :controls="false"
                                placeholder="请输入"
                                :precision="0"
                                :disabled="formDisabled"
                                :min="1"
                                @change="changNum(item.assist_num, item, index)" />
                            时，将自动打上以下所选标签
                        </el-form-item>
                        <el-form-item label-width="108px" label="选择标签" required>
                            <el-button id="audo_tag" :disabled="formDisabled" @click="selecAssistTag(index)">
                                选择标签
                            </el-button>
                            <render-tags v-model:tags="tagList[index]" :closable="computedTagClosable" />
                        </el-form-item>
                    </el-card>
                </div>
            </div>
            <el-button
                v-show="formData.isHight"
                :disabled="formDisabled"
                size="small"
                class="add_rules"
                @click="addAssist">
                添加规则
            </el-button>
        </el-form-item>
        <el-form-item v-if="formData.isHight" label="奖品打标">
            <div class="assisted_num">
                <div class="assisted_card win_box">
                    <el-card
                        v-for="(item, index) in formData.prize_tags"
                        :key="item.help_num"
                        class="card_box"
                        shadow="never">
                        <template #header>
                            <div class="header">
                                <span class="header-tiltle">规则{{ index + 1 }}：</span>
                                <el-icon v-if="!formDisabled" style="cursor: pointer" @click="onDeletePrize(index)">
                                    <delete />
                                </el-icon>
                            </div>
                        </template>
                        <el-form-item label="选择奖品" label-width="80px" required>
                            <el-select
                                id="prize_select"
                                v-model="item.reward_name"
                                :disabled="formDisabled"
                                size="small"
                                placeholder="请选择奖品"
                                @change="changeReward(item.reward_name, index)">
                                <el-option
                                    v-for="item in prizeList"
                                    :key="item.reward_desc || item.reward_title"
                                    :label="item.reward_desc || item.reward_title"
                                    :value="item.reward_desc || item.reward_title"
                                    :disabled="rewardName.includes(item.reward_desc || item.reward_title)" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="80px" label="选择标签" required>
                            <el-button id="prize_tag" :disabled="formDisabled" @click="selectPrizeTag(index)">
                                选择标签
                            </el-button>
                            <render-tags v-model:tags="prizeTags[index]" :closable="computedTagClosable" />
                        </el-form-item>
                    </el-card>
                </div>
            </div>
            <el-button size="small" :disabled="formDisabled" class="add_rules" @click="addPrize">添加规则</el-button>
        </el-form-item>
        <div v-if="formData.isHight" class="el-form-item__label">
            结束后裂变客户打标（活动结束后，活动数据将截止记录，只可在客户列表上筛选客户）
        </div>
        <el-form-item v-if="formData.isHight">
            <div v-if="!isRenderAddEndTagButton" class="assisted_num">
                <div class="assisted_card win_box">
                    <el-card class="card_box" shadow="never">
                        <template #header>
                            <div class="header">
                                <span class="header-tiltle">规则：</span>
                                <el-icon v-if="!formDisabled" style="cursor: pointer" @click="onDeleteEndTag">
                                    <delete />
                                </el-icon>
                            </div>
                        </template>
                        <el-form-item label-width="80px" label="选择标签" required>
                            <el-button id="end_tag" :disabled="formDisabled" @click="selecTag(6)">选择标签</el-button>
                            <render-tags v-model:tags="formData.end_tag" :closable="computedTagClosable" />
                        </el-form-item>
                    </el-card>
                </div>
            </div>
            <el-button v-else size="small" :disabled="formDisabled" class="add_rules" @click="renderEndTag">
                添加规则
            </el-button>
        </el-form-item>
        <div class="title br_top">防刷设置</div>
        <el-form-item label="防刷设置" class="setPrevent">
            <el-switch v-model="formData.flow_restrict" :active-value="1" :inactive-value="2" />
        </el-form-item>
        <!-- <el-form-item required label=""> -->
        <div v-if="formData.flow_restrict == 1" class="flow_restrict">
            <div>在</div>
            <el-input-number
                v-model="formData.flow_second"
                size="small"
                :min="1"
                :controls="false"
                placeholder="请输入"
                :precision="0" />
            <div>秒内，同一用户助力人数超过</div>
            <div>
                <el-input-number
                    v-model="formData.flow_assist_num"
                    size="small"
                    :min="2"
                    :controls="false"
                    placeholder="请输入"
                    :precision="0" />
            </div>
            <div class="tip_text">
                人，自动拉黑
                <el-popover trigger="hover" placement="top-start" effect="dark">
                    <template #reference>
                        <el-icon><QuestionFilled /></el-icon>
                    </template>
                    <template #default>
                        <span>拉黑后该用户无法继续参与活动</span>
                    </template>
                </el-popover>
            </div>
        </div>
        <!-- </el-form-item> -->
    </el-form>
    <ZWDepart ref="DepartRef" :type="1" :limit-num="100" @submit="getDepart" />
    <BatchLabel ref="BatchLabelRef" :title-visible="false" :seach-visible="true" @save="getTags" />
</template>

<script setup lang="ts">
import ZWDepart from '@/components/ZWDepart1.0.vue';
import { getSetionId, IsNotEmpty } from '@/utils/utils';
import BatchLabel from '@/components/BatchLabel1.0.vue';
import renderUserTags from '@/components/zw/activity/render-tags/render-user-tags.vue';
import renderTags from '@/components/zw/activity/render-tags/render-tags.vue';
import { reactive, ref, defineExpose, withDefaults, defineProps, computed, inject } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';

import bus from '@/utils/bus';

/** 进行中、结束的情况下禁用 */
const formDisabled: any = inject('formDisabled');

/** 是否禁用标签关闭 */
const computedTagClosable = computed(() => {
    return !formDisabled?.value && props.pageType !== 'look';
});

interface Props {
    pageType: any;
}
const props = withDefaults(defineProps<Props>(), {
    pageType: ''
});
const emit = defineEmits(['submit']);
const DepartRef = ref<any>(); // 部门弹框类型
const BatchLabelRef = ref<any>(); // 选择标签弹框
const employeeList: any = ref([]);
const AllTags = ref([]); // 选择标签options
const helpTags = ref([]); //助力者
const rewardTags = ref([]); //中奖者
const receiveTags = ref([]); //领奖者
const tagType = ref();
const tagIndex = ref();
const prizeIndex = ref();
const isAssist = ref(false);
const maxAssitNum: any = ref(null);
const formRef = ref<FormInstance>();
const prizeList: any = ref([]);
const formData: any = ref({
    isHight: false,
    employee_ids: [], // 引流员工
    employee_setting: 2, // 引流员工设置
    participate_tag: [], //  参与客户打标
    tag: [{ sort: 1, type: 7, assist_num: null, reward_name: '', tag_ids: [] }],
    prize_tags: [{ sort: 1, type: 3, tag_ids: [], assist_num: 0, reward_name: '' }],
    flow_restrict: 1,
    flow_second: 1,
    flow_assist_num: 50,
    /** 结束后客户打标 */
    end_tag: []
});
const tagList = ref([[]]);
const prizeTags = ref([[]]);
const rules = reactive<FormRules>({
    employee_ids: [{ required: true, message: '请选择引流员工', trigger: 'change' }],
    employee_setting: [{ required: true, message: '请选择引流员工设置', trigger: 'change' }],
    participate_tag: [{ required: true, message: '请选择标签', trigger: 'change' }]
});
//删除助力人数
const onDelete = (index: any) => {
    if (props.pageType !== 'look') {
        formData.value.tag.splice(index, 1);
        ElMessage.success('删除成功');
    }
};
//删除奖品打标
const onDeletePrize = (index: any) => {
    if (props.pageType !== 'look') {
        formData.value.prize_tags.splice(index, 1);
        prizeTags.value.splice(index, 1);
        ElMessage.success('删除成功');
    }
};

/** 控制是否展示结束后裂变规则打标签 */
const isRenderAddEndTagButton = ref(false);
// 删除结束后裂变打标
const onDeleteEndTag = () => {
    isRenderAddEndTagButton.value = true;
};
const renderEndTag = () => {
    isRenderAddEndTagButton.value = false;
};
//添加助力人数
const addAssist = () => {
    if (formData.value.tag.length < 30) {
        formData.value.tag.push({ sort: 1, type: 7, assist_num: null, reward_name: '', tag_ids: [] });
        tagList.value.push([]);
    } else {
        ElMessage.error('最多添加30条规则');
    }
};
// 已选择过的奖品名称
const rewardName = computed(() => {
    return formData.value.prize_tags.filter((item: any) => item.type == 3).map((item: any) => item.reward_name);
});
//添加奖品打标
const addPrize = () => {
    if (formData.value.prize_tags.length < 30) {
        formData.value.prize_tags.push({
            sort: 1,
            type: 3,
            assist_num: 0,
            reward_name: '',
            reward_title: '',
            tag_ids: []
        });
        prizeTags.value.push([]);
    } else {
        ElMessage.error('最多添加30条规则');
    }
};
const changeReward = (value: any, index: any) => {
    formData.value.prize_tags[index].reward_title = value;
};
//打开新建选择人
const openDepart = () => {
    DepartRef.value.isQRAuth = true;
    DepartRef.value.departVisble = true;
    DepartRef.value.selectedMember = [...employeeList.value];
};
// 获取部门成员
const getDepart = (res: any) => {
    employeeList.value = res;
    formData.value.employee_ids = getSetionId('id', employeeList.value);
};
// 员工移除
const handleClose = (tag: any) => {
    employeeList.value = employeeList.value.filter((item: any) => item.id !== tag.id);
    formData.value.employee_ids = getSetionId('id', employeeList.value);
    DepartRef.value.removeItem(tag);
};
//助力人数选择标签
const selecAssistTag = (val: any) => {
    isAssist.value = true;
    tagIndex.value = val;
    BatchLabelRef.value.dialogData.labelChooseType = 2;
    BatchLabelRef.value.hasConditiion = false;
    BatchLabelRef.value.chooseDataArr = [];
    BatchLabelRef.value.chooseDataArr = [...tagList.value[tagIndex.value]];
    BatchLabelRef.value.dialogVisible = true;
};
// 奖品标签
const selectPrizeTag = (val: any) => {
    isAssist.value = false;
    prizeIndex.value = val;
    tagType.value = 5;
    BatchLabelRef.value.dialogData.labelChooseType = 2;
    BatchLabelRef.value.hasConditiion = false;
    BatchLabelRef.value.chooseDataArr = [];
    BatchLabelRef.value.chooseDataArr = [...prizeTags.value[prizeIndex.value]];
    BatchLabelRef.value.dialogVisible = true;
};
// 打开选择标签
const selecTag = (val: any) => {
    isAssist.value = false;
    BatchLabelRef.value.dialogData.labelChooseType = 2;
    BatchLabelRef.value.hasConditiion = false;
    tagType.value = val;
    if (val == 1) {
        BatchLabelRef.value.chooseDataArr = [...AllTags.value];
    } else if (val == 2) {
        BatchLabelRef.value.chooseDataArr = [...helpTags.value];
    } else if (val == 3) {
        BatchLabelRef.value.chooseDataArr = [...rewardTags.value];
    } else if (val == 4) {
        BatchLabelRef.value.chooseDataArr = [...receiveTags.value];
    } else if (val === 6) {
        // 活动结束时的标签
        BatchLabelRef.value.chooseDataArr = [...formData.value.end_tag];
    }
    BatchLabelRef.value.dialogVisible = true;
};
// 获取标签
const getTags = (data: any) => {
    if (isAssist.value) {
        tagList.value[tagIndex.value] = data.data;
        formData.value.tag[tagIndex.value].tag_ids = getSetionId('id', data.data);
    } else {
        if (tagType.value == 1) {
            AllTags.value = data.data;
            formData.value.participate_tag = getSetionId('id', data.data);
        } else if (tagType.value == 2) {
            helpTags.value = data.data;
            formData.value.help_tag = getSetionId('id', data.data);
        } else if (tagType.value == 3) {
            rewardTags.value = data.data;
            formData.value.winner_tag = getSetionId('id', data.data);
        } else if (tagType.value == 4) {
            receiveTags.value = data.data;
            formData.value.receive_tag = getSetionId('id', data.data);
        } else if (tagType.value === 5) {
            prizeTags.value[prizeIndex.value] = data.data;
            formData.value.prize_tags[prizeIndex.value].tag_ids = getSetionId('id', data.data);
        } else if (tagType.value === 6) {
            // 活动结束时的标签
            formData.value.end_tag = data.data;
        }
    }
};
// 移除标签
const onClose1 = (tag: any, val: any, index?: any) => {
    if (val == 1) {
        AllTags.value = AllTags.value.filter(item => item.id != tag.id);
        formData.value.participate_tag = getSetionId('id', AllTags.value);
    } else if (val == 2) {
        helpTags.value = helpTags.value.filter(item => item.id != tag.id);
        formData.value.help_tag = getSetionId('id', helpTags.value);
    } else if (val == 3) {
        rewardTags.value = rewardTags.value.filter(item => item.id != tag.id);
        formData.value.winner_tag = getSetionId('id', rewardTags.value);
    } else if (val == 4) {
        receiveTags.value = receiveTags.value.filter(item => item.id != tag.id);
        formData.value.receive_tag = getSetionId('id', receiveTags.value);
    } else if (val === 6) {
        const inde = prizeTags.value[index].findIndex((item: any) => item.id === tag.id);
        prizeTags.value[index].splice(index, 1);
        formData.value.prize_tags[index].tag_ids = getSetionId('id', prizeTags.value[index]);
    } else {
        tagList.value[index].splice(tag, 1);
        formData.value.tag[index].tag_ids = getSetionId('id', tagList.value[index]);
    }
};
const prizeFindKong = () => {
    const { prize_tags } = formData.value;
    const obj = { name: null, tag: null };
    const resName = prize_tags.some((item: any) => item.reward_name == '');
    const resTags = prize_tags.some((item: any) => item.tag_ids.length == 0);
    obj.name = resName;
    obj.tag = resTags;
    return obj;
};
const clearAssit = (n: any) => {
    formData.value.tag.map((item: any, index: number) => {
        if (index > n) {
            item.assist_num = null;
        }
    });
};
const changNum = (val: any, row: any, index: number) => {
    if (maxAssitNum.value >= val) {
        if (index != 0) {
            if (formData.value.tag[index - 1].assist_num >= val) {
                ElMessage.warning(`【规则${index + 1}】的邀请人数要大于【规则${index}】的邀请人数`);
                formData.value.tag[index].assist_num = null;
                clearAssit(index);
            }
        }
    } else {
        ElMessage.warning('助力人数不得大于设置总人数');
        formData.value.tag[index].assist_num = null;
        return;
    }
};
const onSubmit = async () => {
    if (!formRef.value) return;
    if (formData.value.isHight) {
        if (formData.value.prize_tags.length == 0 && formData.value.tag.length == 0 && isRenderAddEndTagButton.value) {
            ElMessage.warning('助力人数或奖品打标或者结束后裂变客户打标至少设置一个规则');
            return;
        }
        for (let i = 0; i < formData.value.tag.length; i++) {
            if (formData.value.tag[i].assist_num == null) {
                document.querySelector('#audo_tag')?.scrollIntoView({ behavior: 'smooth' });
                ElMessage.warning('请填写邀请人数');
                return;
            }
            if (formData.value.tag[i].tag_ids.length == 0) {
                document.querySelector('#audo_tag')?.scrollIntoView({ behavior: 'smooth' });
                ElMessage.warning('请选择标签');
                return;
            }
        }
        // 如果展示结束后裂变客户标签的情况下需要校验
        if (!isRenderAddEndTagButton.value) {
            if (!formData.value.end_tag?.length) {
                document.querySelector('#end_tag')?.scrollIntoView({ behavior: 'smooth' });
                ElMessage.warning('请选择结束后裂变客户打标签');
                return;
            }
        }
    }
    if (formData.value.isHight && formData.value.prize_tags.length != 0 && prizeFindKong().name) {
        document.querySelector('#prize_select')?.scrollIntoView({ behavior: 'smooth' });
        ElMessage.warning('请选择奖品！');
        return;
    } else if (formData.value.isHight && formData.value.prize_tags.length != 0 && prizeFindKong().tag) {
        document.querySelector('#prize_tag')?.scrollIntoView({ behavior: 'smooth' });
        ElMessage.warning('请选择标签！');
        return;
    }
    await formRef.value.validate((valid: any, fields: any) => {
        if (valid) {
            emit('submit');
        } else {
            ElMessage.warning(Object.values(fields)[0][0].message);
        }
    });
};
//标签会先
const getLook = (v: any, type: number) => {
    if (type === 1) {
        formData.value.tag = v;
        for (let i = 0; i < formData.value.tag.length; i++) {
            tagList.value[i] = v[i].tag_ids;
            formData.value.tag[i].tag_ids = getSetionId('id', v[i].tag_ids);
        }
    } else if (type === 2) {
        formData.value.prize_tags = v;
        for (let i = 0; i < formData.value.prize_tags.length; i++) {
            prizeTags.value[i] = v[i].tag_ids;
            formData.value.prize_tags[i].tag_ids = getSetionId('id', v[i].tag_ids);
        }
    }
};
const prizeData = (data: any) => {
    prizeList.value = data;
};
bus.on('getPrize', prizeData);

defineExpose({
    formData,
    employeeList,
    AllTags,
    helpTags,
    rewardTags,
    receiveTags,
    maxAssitNum,
    onSubmit,
    getLook,
    isRenderAddEndTagButton
});
</script>

<style lang="scss" scoped>
.title {
    margin-bottom: 24px;
    font-size: 16px;
    font-weight: 500;
    color: #33302d;

    &::before {
        content: '';
        display: inline-block;
        width: 4px;
        height: 16px;
        background: #ff6b00;
        margin-right: 6px;
        vertical-align: top;
    }
}

// 员工选择
.form-staffs {
    display: flex;

    .title {
        margin-right: 12px;
    }
}

.staffs_item {
    margin-right: 10px;
}

.staffs_item::before {
    content: '';
    display: inline-block;
    width: 10px;
    height: 11px;
    background: url('@/assets/image/LiveCode/people_icon.png') center/100% no-repeat;
    margin-right: 10px;
}

.radio_group_box {
    font-size: 10px;
    padding: 8px 8px 0;
    background-color: #fffaf9;

    .radio_text {
        font-size: 10px;
        line-height: 16px;
    }
}

.assisted_num {
    display: flex;

    .assisted_title {
        font-size: 14px;
        font-weight: 600;
        margin: 5px 10px 0 0;
    }

    .assisted_card {
        display: flex;
        flex-direction: column;
        min-width: 580px;

        .header {
            display: flex;
            justify-content: space-between;

            .header-tiltle {
                font-size: 15px;
                font-weight: 600;
            }
        }
    }

    .assisted_card .card_box:nth-child(n + 2) {
        margin-top: 10px;
    }
}

:deep(.el-card__body) {
    padding-bottom: 10px;
}

.win_box {
    min-width: 580px;
}

.flow_restrict {
    display: flex;
    align-items: center;
    padding: 0 0 24px 50px;
    font-size: 14px;
    color: #606266;

    div {
        margin: 0 3px;
    }
}

.setPrevent {
    margin-bottom: 12px;
}

.required {
    &::before {
        content: '*';
        color: var(--el-color-danger);
        margin-right: 4px;
    }
}

.tip_text {
    display: flex;
    align-items: center;
}

.br_top {
    border-top: 1px solid #eaeaea;
    padding-top: 24px;
}

.select-staffs {
    margin-top: 6px;
}

// 表单中右侧的提示
.form-tip {
    flex: 1;
    margin-left: 6px;
    color: #999;
    line-height: 18px;
}

// 覆盖el-radio标签。主要是影响助力者员工分配
.form-radio-item {
    :deep(.el-radio) {
        align-items: flex-start;

        .el-radio__input {
            align-self: center;
        }

        // el单选标题
        .el-radio__label {
            display: flex;
            align-items: flex-start;
            white-space: normal;

            .form-tip {
                padding-top: 7px;
            }
        }
    }
}

:deep(.el-button.el-button--primary.is-plain:not(.is-disabled)) {
    --el-button-bg-color: #fff;
    --el-button-border-color: var(--el-color-primary);

    &:hover {
        color: #ff6b00;
        border-color: #ff6b00;
        background-color: #fdefe5;
    }

    &:focus {
        color: #ff6b00;
        background-color: var(--el-button-bg-color);
        border: 1px solid #ffb580;
        outline: none;
    }
}
</style>
